/*
 * @Author: Suo-Yuheng syh15399227325@163.com
 * @Date: 2025-09-08 22:45:00
 * @LastEditors: Suo-Yuheng syh15399227325@163.com
 * @LastEditTime: 2025-09-09 09:17:19
 * @FilePath: /0907/tcp/task.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once
#include <iostream>
#include<string>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>
#include <pthread.h>
#include "log.hpp"
#include "Init.hpp"

using namespace std;

extern log lg;
Init init;


class Task
{
public:
    Task()
    {}
    
    Task(int sockfd, const string &clientip, const uint16_t &clientport)
        :_sockfd(sockfd), _clientip(clientip), _clientport(clientport)
    {
    }

    void Run()
    {
        char buffer[4096];
        // while (true)
        // {
        // Tcp 是面向字节流的，怎么保证 读取上来的数据，是 一个  完整的 报文？
        ssize_t n = read(_sockfd, buffer, sizeof(buffer));
        if (n > 0)
        {
            buffer[n] = 0;
            cout << "client key# " << buffer << endl;
            string echo_string = init.translate(buffer);
            

            int n1 = write(_sockfd, echo_string.c_str(), echo_string.size());
            if(n1 < 0)
            {
                lg(Warning, "write error, errno: %d, errstring: %s", errno, strerror(errno));
            }
        }
        else if (n == 0) // 如果客户端退了,那么 read 的返回值 为 0
        {
            lg(Info, "%s:%d quit, server close sockfd: %d", _clientip.c_str(), _clientport, _sockfd);
            // break;
        }
        else
        {
            // read 出错了,打印客户端信息
            lg(Info, "read error , sockfd: %d, client ip: %s, client port: %d", _sockfd, _clientip.c_str(), _clientport);
            // break;
        }
        close(_sockfd);
        // }
    }

    void operator()()
    {
        Run();
    }

    ~Task()
    {
    }

private:
    int _sockfd;
    string _clientip;
    uint16_t _clientport;
};